/**
 * Created by Administrator on 2017/10/17.
 */
var mongoose = require('mongoose');
const  News=require('../models/news.model');
//增加新的新闻
exports.create=function (req,res,next) {
	const news=new News(req.body);
	news.save()
		.then(data=>{
			res.json(data);
		})
}
//获取新闻
exports.get=function (req,res,next) {
	var id=req.params.id;
	News.findById(id,function (err,data) {
		res.json(data);
	})
}


//更新新闻
exports.updata=function (req,res,next) {
	const news=new  News(req.body);
	var id=req.params.id;
	News.findByIdAndUpdate(id,{$set:req.body},{new:false})
		.then(date=>{
			res.json(date);
		})
}
//删除新闻
exports.remove=function (req,res,next) {
	var id=req.params.id;
	News.findByIdAndRemove(id,function (err,data) {
		res.json(data);
	})
		.then(date=>{
			res.json(date);
		})
}
//获取新闻列表
exports.list=function (req,res,next) {
	var page = (req.body.page)?req.body.page:1;
	var rows =(req.body.limit)?req.body.limit:8;
	var queryCondition={};
	if (req.body.title&&req.body.title.trim().length>0){
		title=req.body.title;
		queryCondition={'title':new RegExp(title,'i')}
	}
	if (req.body.castId&&req.body.castId.trim().length>0){
		castId=req.body.castId;
		queryCondition=Object.assign(queryCondition,{
			castId:castId
		})
	}
	
	
	News.paginate(queryCondition,{sort:{_id:-1},page:parseInt(page),limit:parseInt(rows)},function (err,result) {
		result.rows=result.docs;
		delete result.docs;
		res.json(result);
	});
}
//对新闻进行批量删除
exports.deletes=function (req,res,next) {
	var ids =req.body.ids;
	if (ids.length>0){
		console.log(req.body);
		News.remove({ _id:{$in:ids.split(',')}}).then(data=>{
			res.json({"msg":'删除成功！','status':200});
		})
	}
	else{
		res.json({"msg":'删除失败！','status':404})
	}
}
